package com.lzh.tiktok.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzh.common.utils.JwtUtils;
import com.lzh.tiktok.user.dao.FollowDao;
import com.lzh.tiktok.user.dao.MessageDao;
import com.lzh.tiktok.user.dao.UserDao;
import com.lzh.tiktok.user.entity.FollowEntity;
import com.lzh.tiktok.user.entity.MessageEntity;
import com.lzh.tiktok.user.entity.UserEntity;
import com.lzh.tiktok.user.service.FollowService;
import com.lzh.tiktok.user.vo.FriendInfoResponseVo;
import com.lzh.tiktok.user.vo.FriendVo;
import com.lzh.tiktok.user.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lizhihang
 * @create 2023-01-17 15:27
 */
@Service("followService")
public class FollowServiceImpl extends ServiceImpl<FollowDao, FollowEntity> implements FollowService {
    @Autowired
    UserDao userDao;
    @Autowired
    MessageDao messageDao;

    /**
     * 根据用户id查询关注博主的数量
     *
     * @param userId
     * @return
     */
    @Override
    public Integer getFollowCountByUserId(Integer userId) {
        return this.baseMapper.getFollowCountByUserId(userId);
    }

    /**
     * 根据用户id查询粉丝的数量
     *
     * @param userId
     * @return
     */
    @Override
    public Integer getFollowerByUserId(Integer userId) {
        return this.baseMapper.getFollowerByUserId(userId);
    }

    /**
     * 获取关注列表
     *
     * @param user_id
     * @param token
     * @return
     */
    @Override
    public List<UserVo> getAllFollowList(String user_id, String token) {
        //所有关注信息
        List<FollowEntity> followEntities = this.baseMapper.selectList
                (new QueryWrapper<FollowEntity>().eq("follower_id", user_id));
        //把关注信息转变为关注的博主信息
        List<UserVo> collect = followEntities.stream().map(followEntity -> {
            UserVo userVo = new UserVo();
            //followEntity.getFollowingId()是关注的博主的id
            UserEntity userEntity = userDao.selectById(followEntity.getFollowingId());
            userVo.setId(userEntity.getUserId());
            userVo.setName(userEntity.getUsername());
            //获取关注的博主的关注数量和粉丝数量
            userVo.setFollow_count(this.getFollowCountByUserId(userEntity.getUserId()));
            userVo.setFollower_count(this.getFollowerByUserId(userEntity.getUserId()));
            //是否关注此人
            userVo.setIs_follow(true);
            return userVo;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 获取粉丝列表
     *
     * @param user_id
     * @param token
     * @return
     */
    @Override
    public List<UserVo> getAllFollowerList(String user_id, String token) {
        //所有关注信息
        List<FollowEntity> followEntities = this.baseMapper.selectList
                (new QueryWrapper<FollowEntity>().eq("following_id", user_id));
        //把关注信息转变为粉丝信息
        List<UserVo> collect = followEntities.stream().map(followEntity -> {
            UserVo userVo = new UserVo();
            UserEntity userEntity = userDao.selectById(followEntity.getFollowerId());
            userVo.setId(userEntity.getUserId());
            userVo.setName(userEntity.getUsername());
            userVo.setFollow_count(this.getFollowCountByUserId(Integer.valueOf(followEntity.getFollowerId())));
            userVo.setFollower_count(this.getFollowerByUserId(Integer.valueOf(followEntity.getFollowerId())));
            //查看是否回关该粉丝
            Integer count = this.baseMapper.selectCount(new QueryWrapper<FollowEntity>().eq("follower_id", user_id)
                    .eq("following_id", userVo.getId()));
            if (count != null && count > 0) {
                userVo.setIs_follow(true);
            } else {
                userVo.setIs_follow(false);
            }
            return userVo;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * //当前token用户是否关注了userId这个人
     *
     * @param userId
     * @param token
     * @return
     */
    @Override
    public Boolean isFollowed(Integer userId, String token) {
        Long loginUserId = JwtUtils.getUserId(token);
        Integer count = this.baseMapper.selectCount(new QueryWrapper<FollowEntity>()
                .eq("follower_id", loginUserId).eq("following_id", userId));
        if (count != null && count > 0) {
            return true;
        }
        return false;
    }

    @Override
    public void doAction(String to_user_id, String loginUserId, String action_type) {
        if ("1".equals(action_type)) {
            //关注操作
            FollowEntity followEntity = new FollowEntity();
            followEntity.setFollowerId(Integer.valueOf(loginUserId));
            followEntity.setFollowingId(Integer.valueOf(to_user_id));
            Byte aByte = new Byte("1");
            followEntity.setFollowStatus(aByte);
            this.baseMapper.insert(followEntity);
        } else {
            //取关操作
            this.baseMapper.delete(new QueryWrapper<FollowEntity>()
                    .eq("follower_id", loginUserId)
                    .eq("following_id", to_user_id));
        }
    }

    @Override
    public FriendInfoResponseVo getFriendList(String user_id, String token) {
        FriendInfoResponseVo friendInfoResponseVo = new FriendInfoResponseVo();
        //获取关注列表
        List<UserVo> userVoList1 = getAllFollowList(user_id, token);
        //获取粉丝列表
        List<UserVo> userVoList2 = getAllFollowerList(user_id, token);
        //粉丝列表和关注列表取交集就是好友列表
        List<UserVo> friendList = userVoList1.stream().filter(userVoList2::contains).collect(Collectors.toList());

        //获取和这个好友的最新一条消息

        List<FriendVo> friendList1 = friendList.stream().map(userVo -> {
            FriendVo friendVo = new FriendVo();
            BeanUtils.copyProperties(userVo, friendVo);
            //去数据库中查找和此好友最新的一条消息
            Integer friendUserId = userVo.getId();

            //select * from message
            //where (from_user_id = user_id and to_user_id = friendUserId) or ( from_user_id = friendUserId and to_user_id = user_id)
            //order by create_time limit 1
            MessageEntity messageEntity = messageDao.selectNewMessage(user_id, friendUserId);
            if (messageEntity == null) {
                //设置默认的聊天记录为空
                friendVo.setMessage("");
            } else {
                friendVo.setMessage(messageEntity.getMessage());
            }
            //这里不区分到底是谁发给谁的消息，只要显示和该好友的最新消息即可
            friendVo.setMsgType(0);
            //todo  获取用户的头像 设置默认头像
            friendVo.setAvatar("https://t11.baidu.com/it/u=3221795362,2995410766&fm=58");
            return friendVo;
        }).collect(Collectors.toList());

        friendInfoResponseVo.setUser_list(friendList1);
        friendInfoResponseVo.setStatus_code(0);
        friendInfoResponseVo.setStatus_msg("获取好友列表成功");
        return friendInfoResponseVo;
    }


}
